package bma.common.langutil.concurrent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import bma.common.langutil.core.ObjectPair;
import bma.common.langutil.core.ObjectUtil;

public class ThreadPoolSquare {

	protected static List<ObjectPair<String, Object>> gathers = Collections
			.synchronizedList(new ArrayList<ObjectPair<String, Object>>());

	public static void add(String name, Object threadPool) {
		if (threadPool == null)
			return;
		if (name == null)
			name = "threadpool#" + System.identityHashCode(threadPool);
		for (ObjectPair<String, Object> op : gathers) {
			if (ObjectUtil.equals(op.getAttribute(), threadPool)) {
				op.setValue(name);
				return;
			}
		}
		ObjectPair<String, Object> op = new ObjectPair<String, Object>(name,
				threadPool);
		gathers.add(op);
	}

	public static void remove(String name) {
		Object rm = null;
		for (ObjectPair<String, Object> op : gathers) {
			if (ObjectUtil.equals(op.getValue(), name)) {
				rm = op;
				break;
			}
		}
		if (rm != null)
			gathers.remove(rm);
	}

	public static void remove(Object threadPool) {
		Object rm = null;
		for (ObjectPair<String, Object> op : gathers) {
			if (ObjectUtil.equals(op.getAttribute(), threadPool)) {
				rm = op;
				break;
			}
		}
		if (rm != null) {
			gathers.remove(rm);
		}
	}

	public static List<ObjectPair<String, Object>> list() {
		return new ArrayList<ObjectPair<String, Object>>(gathers);
	}
}
